import {
  CanActivate,
  ExecutionContext,
  HttpException,
  HttpStatus,
  Injectable,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';
import cookie from 'cookie';
import { jwtConstants } from 'src/global-type';

@Injectable()
export class TokenGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    try {
      return true;
      const request = context.switchToHttp().getRequest();
      const cookies = cookie.parse(request.headers.cookie);
      const token = cookies.token;
      const tokenObj = this.jwtService.verify(token, {
        secret: jwtConstants.secret,
      });
      if (tokenObj.id) return true;
      throw new HttpException(
        {
          statusCode: 401,
          message: 'Unauthorized',
        },
        HttpStatus.UNAUTHORIZED,
      );
    } catch (err) {
      throw new HttpException(
        {
          statusCode: 401,
          message: 'error-Unauthorized',
        },
        HttpStatus.UNAUTHORIZED,
      );
    }
  }
}
